from rest_framework.viewsets import GenericViewSet
from django.db.models import Q

from projects.base.pagenations import DefaultPagination
from .models import Group, GroupMessage
from .serializers import GroupSerializer, GroupMessageSerializer
from .validators import GroupValidate, GroupMessageValidate
from ..base.mixin import (CreateModelMixin, ListModelMixin, UpdateModelMixin,
                          RetrieveModelMixin, DestroyModelMixin)


class GroupViewSet(GenericViewSet, CreateModelMixin, ListModelMixin, UpdateModelMixin,
                   RetrieveModelMixin, DestroyModelMixin):
    # lookup_field = "uid"
    queryset = Group.objects
    serializer_class_table = {
        "list": GroupSerializer,
        "retrieve": GroupSerializer,
        "destroy": GroupSerializer,
        "create": GroupValidate,
        "update": GroupValidate,
    }

    def get_serializer_class(self):
        return self.serializer_class_table.get(
            self.action, None
        )

    def get_queryset(self):
        # 作为群主, 作为群成员的所有
        uid = self.request.query_params.get("uid")
        group_list = Group.objects.filter(Q(creator=uid) | Q(member__uid=uid)).distinct()
        return group_list


class GroupMessageViewSet(GenericViewSet, CreateModelMixin, ListModelMixin,
                          RetrieveModelMixin, DestroyModelMixin):
    queryset = GroupMessage.objects
    serializer_class_table = {
        "create": GroupMessageValidate,
        "list": GroupMessageSerializer,
        "retrieve": GroupMessageSerializer,
    }
    pagination_class = DefaultPagination

    def get_serializer_class(self):
        return self.serializer_class_table.get(
            self.action, None
        )

    def get_queryset(self):
        group_id = self.request.query_params.get("group")
        queryset = GroupMessage.objects.filter(group_id=group_id).all()
        return queryset

